<template>
  <div>
    <a-modal v-model:visible="visible" :title="getTitle" width="1000px" @cancel="cancel">
      <template #footer>
        <a-button
          type="primary"
          v-if="
            formData.cloud_type == 1 ||
            (formData.cloud_type == 2 && getTitle == '新建') ||
            (formData.cloud_type == 3 && getTitle == '新建')
          "
          @click.stop="handleOk"
          >确定</a-button
        >
        <a-button @click.stop="cancel">取消</a-button>
      </template>
      <div class="copypermis">
        <a-form
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :model="formData"
          ref="formRef"
          :rules="
            formData.cloud_type == 1 ? hsrules : formData.cloud_type == 2 ? hwrules : hwrulesedge
          "
        >
          <a-row>
            <a-col :span="12">
              <div class="title">基础配置</div>
              <a-form-item label="类型" name="cloud_type">
                <a-select
                  :disabled="getTitle == '修改'"
                  placeholder="请选择类型"
                  v-model:value="formData.cloud_type"
                  @change="handleChangecloud_type"
                  :options="typeoptions"
                />
              </a-form-item>
              <a-form-item label="应用名称" name="app_name">
                <a-input
                  v-model:value="formData.app_name"
                  placeholder="请输入应用名称"
                  :disabled="isDisabled"
                />
              </a-form-item>
              <a-form-item
                label="状态"
                name="enable"
                v-if="(formData.cloud_type == 2 || formData.cloud_type == 3) && getTitle == '修改'"
              >
                <a-switch
                  v-model:checked="formData.enable"
                  @change="(e) => changeEnableStatus(e, formData.id)"
                  checked-children="开"
                  un-checked-children="关"
                  :checkedValue="checkedValue"
                  :unCheckedValue="unCheckedValue"
                />
              </a-form-item>
              <a-form-item
                label="状态"
                name="enable"
                v-if="formData.cloud_type == 1 && getTitle == '修改'"
              >
                <a-switch
                  v-model:checked="formData.enable"
                  checked-children="开"
                  un-checked-children="关"
                  :checkedValue="checkedValue"
                  :unCheckedValue="unCheckedValue"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <div class="title">上云配置</div>
              <!-- 环思/阿里云上云配置 -->
              <div v-show="formData.cloud_type == 1">
                <a-form-item label="域名/IP" name="host">
                  <a-input v-model:value="formData.host" placeholder="请输入域名/IP*" />
                </a-form-item>
                <a-form-item label="端口" name="port">
                  <a-input v-model:value="formData.port" placeholder="请输入端口" />
                </a-form-item>
                <a-form-item label="令牌" name="token">
                  <a-input v-model:value="formData.token" placeholder="请输入令牌" />
                </a-form-item>
              </div>
              <!-- 华为(iotDA) -->
              <div v-show="formData.cloud_type == 2">
                <a-form-item label="版本选择" name="huawei_cloud_type">
                  <a-select
                    :disabled="isDisabled"
                    placeholder="请选择版本"
                    v-model:value="formData.huawei_cloud_type"
                    :options="versionOptions"
                  />
                </a-form-item>
                <a-form-item label="key" name="access_key">
                  <a-input
                    v-model:value="formData.access_key"
                    placeholder="请输入key"
                    :disabled="isDisabled"
                  />
                </a-form-item>
                <a-form-item label="Secret" name="secret_access_key">
                  <a-input
                    v-model:value="formData.secret_access_key"
                    placeholder="请输入Secret"
                    :disabled="isDisabled"
                  />
                </a-form-item>
                <a-form-item label="项目id" name="project_id">
                  <a-input
                    v-model:value="formData.project_id"
                    placeholder="请输入项目id"
                    :disabled="isDisabled"
                  />
                </a-form-item>
                <a-form-item label="IP地址" name="endpoint">
                  <a-input
                    v-model:value="formData.endpoint"
                    placeholder="请输入IP地址"
                    :disabled="isDisabled"
                  />
                </a-form-item>
              </div>
              <!-- 华为(iotDA) -->
              <div v-show="formData.cloud_type == 3">
                <a-form-item label="key" name="access_key">
                  <a-input
                    v-model:value="formData.access_key"
                    placeholder="请输入key"
                    :disabled="isDisabled"
                  />
                </a-form-item>
                <a-form-item label="Secret" name="secret_access_key">
                  <a-input
                    v-model:value="formData.secret_access_key"
                    placeholder="请输入Secret"
                    :disabled="isDisabled"
                  />
                </a-form-item>
                <a-form-item label="项目id" name="project_id">
                  <a-input
                    v-model:value="formData.project_id"
                    placeholder="请输入项目id"
                    :disabled="isDisabled"
                  />
                </a-form-item>
                <a-form-item label="APPID" name="app_id">
                  <a-input
                    v-model:value="formData.app_id"
                    placeholder="请输入华为云资源空间id"
                    :disabled="isDisabled"
                  />
                </a-form-item>
                <!-- <a-form-item label="边缘节点host" name="edge_host">
                  <a-input
                    v-model:value="formData.edge_host"
                    placeholder="请输入边缘节点host"
                    :disabled="isDisabled"
                  />
                </a-form-item> -->
                <a-form-item label="边缘节点id:" name="edge_node_id">
                  <a-input
                    v-model:value="formData.edge_node_id"
                    placeholder="请输入边缘节点id"
                    :disabled="isDisabled"
                  />
                </a-form-item>

                <a-form-item label="IP地址" name="edge_host">
                  <a-input
                    v-model:value="formData.edge_host"
                    placeholder="请输入边缘节点ip地址"
                    :disabled="isDisabled"
                  />
                </a-form-item>
              </div>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item
                label="配置"
                name="config"
                v-show="formData.cloud_type == 1"
                :label-col="{ span: 2 }"
                :wrapper-col="{ span: 22 }"
              >
                <CodeEditor
                  v-model:value="formData.config"
                  placeholder="请输入配置"
                  style="height: 200px"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, computed, unref, createVNode } from 'vue';
  import {
    addServiceApi,
    editServiceApi,
    getServiceApiByID,
    serviceEnableStatus,
  } from '/@/api/sys/gateway/gateway';
  import { CodeEditor } from '/@/components/CodeEditor';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  export default defineComponent({
    components: { CodeEditor },
    props: ['isUpdate'],
    emits: ['success'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      const checkedValue = ref(1);
      const unCheckedValue = ref(0);
      //显示隐藏弹框
      const visible = ref(false);
      const isDisabled = ref(false);
      //是否是修改页面
      //表单数据
      const formData = <any>reactive({
        cloud_type: 1,
        host: '',
        port: '',
        token: '',
        config: '',
        app_name: '',
      });
      // 云平台类型
      const typeoptions = reactive([
        { value: 1, label: '环思物联平台' },
        { value: 2, label: '华为云物联平台(iotDA)' },
        { value: 3, label: '华为云物联平台(iotEdge)' },
      ]);
      //版本选择
      const versionOptions = reactive([
        { value: 1, label: '基础版' },
        { value: 2, label: '标准版' },
        { value: 3, label: '企业版' },
      ]);
      //环思平台表单验证
      let hsrules = {
        app_name: {
          required: true,
          message: '请输入应用名称',
        },
        host: {
          required: true,
          message: '请输入域名/IP',
        },
        config: {
          required: true,
          message: '请输入配置',
        },
      };
      //华为平台iotda表单验证
      let hwrules = {
        app_name: {
          required: true,
          message: '请输入应用名称',
        },
        access_key: {
          required: true,
          message: '请输入key',
        },
        secret_access_key: {
          required: true,
          message: '请输入secret',
        },
        project_id: {
          required: true,
          message: '请输入项目id',
        },
        endpoint: {
          required: true,
          message: '请输入接入地址',
        },
      };

      //华为平台iotedge表单验证
      let hwrulesedge = {
        app_name: {
          required: true,
          message: '请输入应用名称',
        },
        access_key: {
          required: true,
          message: '请输入key',
        },
        secret_access_key: {
          required: true,
          message: '请输入secret',
        },
        project_id: {
          required: true,
          message: '请输入项目id',
        },

        edge_host: {
          required: true,
          message: '请输入边缘节点ip地址',
        },
        edge_node_id: {
          required: true,
          message: '请输入边缘节点id',
        },
        app_id: {
          required: true,
          message: '请输入华为云资源空间id',
        },
      };
      //更新云服务启用状态
      function changeEnableStatus(e, id) {
        Modal.confirm({
          title: '温馨提示',
          icon: createVNode(ExclamationCircleOutlined),
          content: `确定${formData.enable == 0 ? '停用' : '启用'}吗`,
          okText: '确认',
          cancelText: '取消',
          onOk() {
            serviceEnableStatus({
              id: id,
              enable: parseInt(e),
            }).then(() => {
              createMessage.success(e == 1 ? '启用成功' : '停用成功');
            });
          },
          onCancel() {
            formData.enable = 1;
          },
        });
      }

      //获取编辑详情
      function getediteDetail(e) {
        console.log(e);
        getServiceApiByID({
          id: e,
        }).then((res) => {
          Object.keys(formData).map((key) => {
            delete formData[key];
          });
          formData.id = res.id;
          isDisabled.value =
            (res.cloud_type == 2 || res.cloud_type == 3) && props.isUpdate ? true : false;
          if (res.cloud_type == 1) {
            formData.cloud_type = res.cloud_type;
            formData.host = res.host;
            formData.port = res.port;
            formData.token = res.token;
            formData.config = res.config;
            formData.app_name = res.app_name;
            formData.enable = res.enable;
          } else if (res.cloud_type == 2) {
            formData.cloud_type = 2;
            formData.access_key = res.access_key;
            formData.secret_access_key = res.secret_access_key;
            formData.project_id = res.project_id;
            formData.endpoint = res.endpoint;
            formData.app_name = res.app_name;
            formData.huawei_cloud_type = res.huawei_cloud_type;
            formData.enable = res.enable;
          } else if (res.cloud_type == 3) {
            formData.cloud_type = 3;
            formData.access_key = res.access_key;
            formData.secret_access_key = res.secret_access_key;
            formData.project_id = res.project_id;
            formData.app_name = res.app_name;
            formData.enable = res.enable;
            formData.edge_host = res.edge_host;
            formData.edge_node_id = res.edge_node_id;
            formData.app_id = res.app_id;
          }
          visible.value = true;
        });
      }

      //点击选择平台类型 1是环思  2是华为iotDA  3是华为iotEdge
      const handleChangecloud_type = (e) => {
        Object.keys(formData).map((key) => {
          delete formData[key];
        });
        if (e == 1) {
          formData.cloud_type = 1;
          formData.host = '';
          formData.port = '';
          formData.token = '';
          formData.config = {};
          formData.app_name = '';
        } else if (e == 2) {
          formData.cloud_type = 2;
          formData.access_key = '';
          formData.secret_access_key = '';
          formData.project_id = '';
          formData.endpoint = '';
          formData.app_name = '';
          formData.huawei_cloud_type = undefined;
        } else if (e == 3) {
          formData.cloud_type = 3;
          formData.access_key = '';
          formData.secret_access_key = '';
          formData.project_id = '';
          formData.app_name = '';
          formData.edge_host = '';
          formData.edge_port = '';
          formData.edge_node_id = '';
        }
      };
      const formRef = ref();
      const getTitle = computed(() => (!unref(props.isUpdate) ? '新建' : '修改'));
      //保存
      const handleOk = () => {
        formRef.value
          .validate()
          .then(() => {
            if (props.isUpdate) {
              if (isJson(formData.config) == false) {
                formData.config = JSON.parse(formData.config || '');
              }
              editServiceApi(formData).then((res) => {
                emit('success', { isUpdate: unref(props.isUpdate) });
                cancel();
                formRef.value.resetFields();
              });
            } else {
              if (formData.cloud_type == 1) {
                if (isJson(formData.config) == false) {
                  formData.config = JSON.parse(formData.config || '');
                }
              }
              addServiceApi(formData).then((res) => {
                emit('success', { isUpdate: unref(props.isUpdate) });
                formRef.value.resetFields();
                cancel();
              });
            }
          })
          .catch((error) => {
            console.log('error', error);
          });
      };
      //判断是否是json数据
      const isJson = function (obj) {
        var isjson =
          typeof obj == 'object' &&
          Object.prototype.toString.call(obj).toLowerCase() == '[object object]' &&
          !obj.length;
        return isjson;
      };
      //取消
      const cancel = () => {
        visible.value = false;
        formData.cloud_type = 1;
        handleChangecloud_type(1);
      };
      return {
        changeEnableStatus,
        isDisabled,
        getediteDetail,
        getTitle,
        formRef,
        hsrules,
        hwrules,
        handleChangecloud_type,
        typeoptions,
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
        visible,
        formData,
        handleOk,
        cancel,
        versionOptions,
        checkedValue,
        unCheckedValue,
        hwrulesedge,
      };
    },
  });
</script>

<style lang="less">
  .copypermis {
    padding: 20px;
    box-sizing: border-box;
    .title {
      margin-bottom: 20px;
      font-weight: 500;
    }
  }
</style>
